<template>
  <div class="main_box" style="padding:10px">
    <div class="add_wrap">
      <div class="tit">
        <h2>{{ dataForm.activityId ? "编辑活动" : "新增活动" }}</h2>
        <el-button
          type="success"
          plain
          size="small"
          icon="fa fa-mail-forward"
          @click="returnList"
          >返回</el-button
        >
      </div>
      <el-form
        :model="dataForm"
        ref="dataForm"
        label-width="200px"
        :rules="roleRules"
      >
        <el-row>
          <el-form-item prop="activityName" label="活动名">
            <el-input v-model="dataForm.activityName"></el-input>
          </el-form-item>
          <el-form-item prop="activityType" label="活动类型">
            <el-select v-model="dataForm.activityType" @change="handleActivityTypeChange">
              <el-option
                v-for="item in activityTypeList"
                :label="item.name"
                :value="item.id"
                :key="item.id"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item prop="mainImage" label="活动主图">
            <upload-img
              class="upload-img"
              @uploadFileList="getImgUrl"
              folder="activity"
            >
              <img
                v-if="dataForm.mainImage"
                width="100%"
                :src="dataForm.mainImage"
                alt=""
              />
              <div class="tip" v-if="!dataForm.mainImage">
                <i class="el-icon-upload"></i>
                <div class="el-upload__text">
                  将图片拖到此处，或<em>点击上传</em>
                </div>
              </div>
            </upload-img>
          </el-form-item>
          <el-form-item prop="classsifyList" label="分类名">
            <el-cascader
              v-model="dataForm.classsifyList"
              :props="{ label: 'name', value: 'id' }"
              :options="classTreeList"
            ></el-cascader>
          </el-form-item>

          <el-form-item prop="mainBtnName" label="主按钮名称">
            <el-input v-model="dataForm.mainBtnName" clearable></el-input>
          </el-form-item>
          <el-form-item prop="date" label="活动展示时间">
            <el-date-picker
              v-model="dataForm.date"
              type="datetimerange"
              format="yyyy-MM-dd HH:mm"
              value-format="yyyy-MM-dd HH:mm:ss"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              @change="handleDateChange"
            >
            </el-date-picker>
          </el-form-item>
          <el-form-item prop="buyWay" label="购买方式" v-show="dataForm.activityType==1">
            <el-select v-model="dataForm.buyWay" placeholder="请选择购买方式">
              <el-option
                v-for="item in buyWayList"
                :value="item.id"
                :label="item.name"
                :key="item.id"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item prop="addressList" label="地址">
            <Address
              :addressList="dataForm.addressList"
              @getAddress="getAddress"
              :level="3"
              :isCheckStrictly="true"
            />
          </el-form-item>
          <el-form-item label="小区" prop="villageId">
            <el-select
              v-model="dataForm.villageId"
              clearable
              filterable
              @change="handleVillageChange"
            >
              <el-option
                v-for="item in villageList"
                :value="item.id"
                :label="item.name"
                :key="item.id"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item prop="keywords" label="关键字">
            <el-input v-model="dataForm.keywords"></el-input>
          </el-form-item>

          <el-form-item prop="sort" label="排序">
            <el-input type="number" v-model.number="dataForm.sort"></el-input>
          </el-form-item>
          <el-form-item prop="introduce" label="活动简介">
            <el-input type="textarea" v-model="dataForm.introduce"></el-input>
          </el-form-item>
          <RichEditor
            :richText="dataForm.content"
            @getRichText="getRichText"
          ></RichEditor>
        </el-row>
        <div class="tit">
          <h2>按钮</h2>
          <el-button
            type="success"
            circle
            icon="el-icon-plus"
            plain
            @click="addItem"
          ></el-button>
        </div>
        <el-row>
          <el-table :data="dataForm.list" style="width: fit-content;" row-key="id">
            <el-table-column label="操作" width="140" align="center">
              <template slot-scope="scope">
                <el-button
                  icon="el-icon-minus"
                  circle
                  type="danger"
                  plain
                  @click="dataForm.list.splice(scope.$index, 1)"
                ></el-button>
              </template>
            </el-table-column>
            <el-table-column label="按钮名称" width="200px" align="center">
              <template slot-scope="scope">
                <el-input v-model="scope.row.btnName"></el-input>
              </template>
            </el-table-column>
            <el-table-column label="产品可购买时间" width="498px" v-if="dataForm.activityType == 1" align="center">
              <template slot-scope="scope">
                <el-date-picker
                  v-model="scope.row.date"
                  type="datetimerange"
                  format="yyyy-MM-dd HH:mm"
                  value-format="yyyy-MM-dd HH:mm:ss"
                  start-placeholder="开始时间"
                  end-placeholder="结束时间"
                  :picker-options="{ disabledDate: disabledDate }"
                >
                </el-date-picker>
              </template>
            </el-table-column>
            <el-table-column
              label="货品编号"
              v-if="dataForm.activityType == 1"
              width="200px"
              align="center"
            >
              <template slot-scope="scope">
                <el-input v-model="scope.row.serverCode"> </el-input>
              </template>
            </el-table-column>
          </el-table>
        </el-row>
        <el-row>
          <el-form-item>
            <el-button plain type="primary" @click="sureClick">保 存</el-button>
            <el-button plain @click="returnList">取 消</el-button>
          </el-form-item>
        </el-row>
      </el-form>
    </div>
  </div>
</template>

<script>
import * as message from "@/constants/message";
import TagRuleApi from "@/api/operation/tagModel";
import Address from "@/components/Address";
import RichEditor from "../../components/RichEditor.vue";
import UploadImg from "@/components/UploadImg";
import VillageApi from "@/api/address/village";
import ActivityApi from "@/api/operation/activity";
import { nanoid } from "nanoid";
import Sortable from "sortablejs";
export default {
  data() {
    return {
      dataForm: {
        activityId: "",
        activityType:"",
        activityName: "",
        classsifyList: [],
        villageId: "",
        villageName: "",
        addressList: [],
        keywords: "",
        mainBtnName: "",
        sort: "",
        mainImage: "",
        introduce: "",
        content: "",
        buyWay: "",
        date: null,
        list: [{ id: nanoid(), btnName: "", date: null, serverCode: "" }]
      },
      activityTypeList: [{ id: 1, name: "产品" }, { id: 2, name: "通知" }],
      buyWayList: [
        { id: 11, name: "快捷支付下单" },
        { id: 12, name: "补差价支付下单" },
        { id: 13, name: "详情页下单" },
        { id: 14, name: "结算页下单" }
      ],
      classTreeList: [],
      villageList: [],
      loadingIns: false,
      roleRules: {
        activityName: [
          { required: true, message: "请输入活动名", trigger: "blur" }
        ],
        activityType: [
          { required: true, message: "请选择活动类型", trigger: "blur" }
        ],
        classsifyList:[
          {required:true,message:"请选择分类",trigger:"change"}
        ],
        mainBtnName:[
          {required:true,message:"请输入主按钮名称",trigger:"blur"}
        ],
        date:[
          {required:true,message:"请选择活动展示时间",trigger:"change"}
        ],
        introduce:[
          {required:true,message:"请输入活动简介",trigger:"blur"}
        ],
        mainImage: [
          { required: true, message: "请上传活动主图", trigger: "change" }
        ],
        addressList: [
          { required: true, message: "请选择地址", trigger: "change" }
        ],
        keywords: [{ required: true, message: "请输入关键字", trigger: "blur" }]
      }
    };
  },
  components: {
    UploadImg,
    Address,
    RichEditor
  },
  watch: {
    "dataForm.activityType":{
      handler(val){
        if (val == 1) {
        this.$set(this.roleRules,"buyWay",[{required:true,message:"请选择购买方式",trigger:"blur"}])
      } else if (val == 2) {
        this.$delete(this.roleRules,"buyWay")
      }
      this.$nextTick(()=>{
        this.$refs.dataForm.clearValidate()
      })
      },
      immediate:true
    }
  },
  mounted() {
    this.init();
  },
  updated(){
  	console.log("更新")
  },
  methods: {
    init() {
      if (this.$route.query.id) {
        this.dataForm.activityId = this.$route.query.id;
        this.getData();
      }
      this.setSort();
      TagRuleApi.classifyTree().then(res => {
        this.classTreeList = res.data;
      });
    },
    keydown(e) {
      if (e.keyCode == 32) {
        e.returnValue = false;
      }
    },
    getData() {
      const { dataForm } = this;
      ActivityApi.getActivity({
        id: dataForm.activityId
      }).then(res => {
        this.$Utils.bindingBean(dataForm, res.data);

        const data = res.data;

        // 部门格式化
        const departIds = [];
        data.firstClassifyId ? departIds.push(data.firstClassifyId) : "";
        data.secondClassifyId ? departIds.push(data.secondClassifyId) : "";
        data.thirdClassifyId ? departIds.push(data.thirdClassifyId) : "";
        dataForm.classsifyList = departIds;

        // 地址格式化
        const addressArr = [];
        data.provinceId ? addressArr.push(data.provinceId) : "";
        data.cityId ? addressArr.push(data.cityId) : "";
        data.areaId ? addressArr.push(data.areaId) : "";
        data.provinceName ? addressArr.push(data.provinceName) : "";
        data.cityName ? addressArr.push(data.cityName) : "";
        data.areaName ? addressArr.push(data.areaName) : "";
        dataForm.addressList = addressArr;
        if (data.provinceId) {
          this.getVillageList();
        }

        // 时间格式化
        dataForm.date = data.showBeginDate
          ? [data.showBeginDate, data.showEndDate]
          : null;

        // 按钮列表添加id,因为排序需要id作为key
        dataForm.list.forEach(item=>{
          this.$set(item,"id",nanoid())
          this.$set(item,"date",[item.buyBeginDate,item.buyEndDate])
        })

      });
    },
    // 活动类型改变
    handleActivityTypeChange(){
      const {activityType,list} = this.dataForm
      if (activityType == 1) {
        list.forEach(item =>{
          this.$set(item, "serverCode", "")
          this.$set(item, "date", "")
        } );
      } else if (activityType == 2) {
        list.forEach(item => {
          this.$delete(item, "serverCode")
          this.$delete(item, "date")
        });
        if(list.length>3)list.splice(3)
      }
    },
    // 设置时间
    disabledDate(time){
      const {date} = this.dataForm
      if(!date) return true
      if(time>=new Date(date[0])&&time<=new Date(date[1]))return false
      return true
    },
     // 设置排序
     setSort() {
      new Sortable(document.querySelector(".el-table tbody"), {
        onEnd: e => {
          const { list } = this.dataForm;
          const val = list.splice(e.oldIndex, 1);
          list.splice(e.newIndex, 0, val[0]);
        }
      });
    },
    // 新增一条数据
    addItem(){
      const {list,activityType} = this.dataForm
      if(activityType==2&&list.length==3){
        return this.$message.error("通知类型最多只可以设置三个按钮")
      }
      list.push(this.$options.data().dataForm.list[0])
    },
    getRichText(val) {
      this.dataForm.content = val;
    },
    getAddress({
      provinceId,
      provinceName,
      cityId,
      cityName,
      areaId,
      areaName
    }) {
      const { dataForm } = this;
      dataForm.villageId = "";
      dataForm.villageName = "";
      this.villageList = [];
      let addressList = [];
      if (provinceId) addressList = [provinceId, provinceName];
      if (cityId)addressList = addressList.concat([cityId, cityName]);
      if (areaId)addressList = addressList.concat([areaId, areaName]);
      dataForm.addressList = addressList
      this.getVillageList();
    },
    async getVillageList() {
      const addressIds = this.dataForm.addressList.filter(item => Number(item));
      console.log(this.dataForm.addressList,addressIds)
      const [provinceId, cityId, areaId] = addressIds;
      if (!provinceId) return;
      const params = {
        provinceId,
        cityId,
        areaId
      };
      const res = await VillageApi.villageList(params);
      this.villageList = res.data;
    },
    handleVillageChange(e) {
      const { dataForm, villageList } = this;
      if (e) {
        dataForm.villageName = villageList.find(item => item.id == e).name;
      } else {
        dataForm.villageName = "";
      }
    },
    handleDateChange(val) {
      const { dataForm } = this;
      dataForm["showBeginDate"] = val ? val[0] : "";
      dataForm["showEndDate"] = val ? val[1] : "";
      dataForm.list.forEach(item=>item.date = null)
    },
    getImgUrl(val) {
      if (val.length > 0) {
        this.dataForm.mainImage = val[0];
      }
    },
    // 格式化数据为提交所需的格式，同时校验没有校验的数据
    checkData() {
      const { dataForm, classTreeList } = this;
      let {
        date,
        classsifyList: [firstClassifyId, secondClassifyId, thirdClassifyId],
        addressList,
        introduce,
        content,
        list,
        activityType
      } = dataForm;


      const tempData = {};
      // 去空格
      dataForm.introduce = introduce.replace(/\s/g, "");

      // 处理时间
      tempData.showBeginDate = date ? date[0] : "";
      tempData.showEndDate = date ? date[1] : "";

      // 处理分类
      const [first, second, third] = this.$Utils.filterTreeToArr(
        classTreeList,
        { id: thirdClassifyId || secondClassifyId || firstClassifyId },
        "id"
      );
      tempData.firstClassifyId = first ? first.id : "";
      tempData.firstClassifyName = first ? first.name : "";
      tempData.secondClassifyId = second ? second.id : "";
      tempData.secondClassifyName = second ? second.name : "";
      tempData.thirdClassifyId = third ? third.id : "";
      tempData.thirdClassifyName = third ? third.name : "";

      // 处理地址
      const addressIds = [];
      const addressNames = [];
      addressList = addressList.forEach(item =>
        Number(item) ? addressIds.push(item) : addressNames.push(item)
      );
      tempData.provinceId = addressIds[0] ? addressIds[0] : "";
      tempData.provinceName = addressNames[0] ? addressNames[0] : "";
      tempData.cityId = addressIds[1] ? addressIds[1] : "";
      tempData.cityName = addressNames[1] ? addressNames[1] : "";
      tempData.areaId = addressIds[2] ? addressIds[2] : "";
      tempData.areaName = addressNames[2] ? addressNames[2] : "";

      // 处理按钮表格
      tempData.list = [];
      for (let i=0;i<list.length;i++) {
        const item = {...list[i]}
        if (!item.btnName) {
           this.$message.error("请输入按钮名称");
           return
        }
        if (activityType == 1 && !item.serverCode) {
           this.$message.error("请输入货品编号");
           return
        }

        if (activityType == 1&&!item.date) {
           this.$message.error("请选择产品购买时间");
           return
        }

        // 去除id和date,同时添加排序
        delete item.id
        item.sort = i+1
        if(activityType==1){
          item.buyBeginDate = item.date[0] || ""
          item.buyEndDate = item.date[1] || ""
          delete item.date
        }
        tempData.list.push(item);
      }
      return tempData;
    },
    async sureClick() {
      await this.$refs.dataForm.validate();
      const tempData = this.checkData();
      if (!tempData) return;

      await this.$confirm(
        message.MSG_CONFIRM_SAVE_ALTER,
        message.TITLE_PROMPT,
        {}
      );

      const params = {
        activityName: "",
        activityType:"",
        keywords: "",
        mainBtnName: "",
        sort: "",
        mainImage: "",
        introduce:"",
        content: "",
        villageId:"",
        villageName:"",
        // buyWay: ""
      };
      const { activityId,activityType } = this.dataForm;
      if(activityType==1){
        params.buyWay = ""
      }
      // 合并参数
      this.$Utils.bindingBean(params, this.dataForm);
      Object.assign(params, tempData);

      if (activityId) {
        params.activityId = activityId;
        this.editData(params);
      } else {
        this.addData(params);
      }
    },
    addData(params) {
      ActivityApi.addActivity(params).then(res => {
        this.$Utils.notifySuccess();
        this.returnList();
      });
    },
    editData(params) {
      ActivityApi.editActivity(params).then(res => {
        this.$Utils.notifySuccess();
        this.returnList();
      });
    },
    returnList() {
      this.$store.dispatch("delView", this.$route);
      this.$router.push({
        path: "/operation/activityManagement"
      });
    }
  }
};
</script>
<style lang="scss">
@import "@/assets/css/views/add.scss";
@import "@/assets/css/views/content.scss";
</style>
<style lang="scss" scoped>
.upload-img {
  &::v-deep .el-upload {
    width: 100%;

    .el-upload-dragger {
      width: 100%;
      display: flex;
      justify-content: space-around;
      align-items: center;

      .tip {
        padding-bottom: 30px;
      }
    }
  }
}

.preview {
  width: 100%;
  min-height: 300px;
  border: 1px solid black;

  .content {
  }
}
</style>
